package com.atguigu.gulimall.product.service.impl;

import com.atguigu.common.constant.ProductConstant;
import com.atguigu.common.to.SkuEsModel;
import com.atguigu.common.to.SkuReductionTO;
import com.atguigu.common.to.SpuBrandTO;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.product.dao.*;
import com.atguigu.gulimall.product.entity.*;
import com.atguigu.gulimall.product.feign.CouponFeignService;
import com.atguigu.gulimall.product.feign.SearchFeignService;
import com.atguigu.gulimall.product.feign.WareFeignService;
import com.atguigu.gulimall.product.service.*;
import com.atguigu.gulimall.product.vo.*;
import lombok.extern.slf4j.Slf4j;
import com.alibaba.fastjson.TypeReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

@Slf4j
@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

    @Autowired
    private SpuInfoDescService spuInfoDescService;

    @Autowired
    private SpuImagesService spuImagesService;

    @Autowired
    private ProductAttrValueService productAttrValueService;

    @Autowired
    private SkuInfoService skuInfoService;

    @Autowired
    private SkuImagesService skuImagesService;

    @Autowired
    private SkuSaleAttrValueService skuSaleAttrValueService;

    @Autowired
    private AttrService attrService;

    @Autowired
    private ProductAttrValueService attrValueService;

    @Autowired
    private CouponFeignService couponFeignService;

    @Autowired
    private BrandService brandService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private WareFeignService wareFeignService;

    @Autowired
    private SearchFeignService searchFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );
        return new PageUtils(page);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveSpuInfo(SpuSaveVO saveVO) {
        //保存基本信息 pms_spu_info
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
        BeanUtils.copyProperties(saveVO, spuInfoEntity);
        spuInfoEntity.setCreateTime(new Date());
        spuInfoEntity.setUpdateTime(new Date());
        this.save(spuInfoEntity);
        //保存spu的描述图片 pms_spu_info_desc
        Long spuInfoId = spuInfoEntity.getId();
        log.error("SpuInfoEntity:{}", spuInfoEntity);
        List<String> decript = saveVO.getDecript();
        spuInfoDescService.saveDecript(spuInfoId, decript);

        //保存spu的图片集 pms_spu_images
        List<String> images = saveVO.getImages();
        spuImagesService.saveImages(spuInfoId,images);

        //保存spu的规格参数 pms_product_attr_value
        List<BaseAttrs> baseAttrs = saveVO.getBaseAttrs();
        if(!ObjectUtils.isEmpty(baseAttrs)){
            List<ProductAttrValueEntity> attrValueEntityList = baseAttrs.stream().map(item -> {
                Long attrId = item.getAttrId();
                AttrEntity attrEntity = attrService.getById(attrId);
                ProductAttrValueEntity valueEntity = new ProductAttrValueEntity();
                valueEntity.setSpuId(spuInfoId);
                valueEntity.setAttrId(attrId);
                valueEntity.setAttrName(attrEntity.getAttrName());
                valueEntity.setAttrValue(item.getAttrValues());
                valueEntity.setQuickShow(item.getShowDesc());
                return valueEntity;
            }).collect(Collectors.toList());
            productAttrValueService.saveValueAttr(attrValueEntityList);
        }
        //保存spu的积分信息 gulimall_sms -> sms_spu_bounds
        Bounds bounds = saveVO.getBounds();
        if (!ObjectUtils.isEmpty(bounds)) {
            SpuBrandTO spuBrandTO = new SpuBrandTO();
            BeanUtils.copyProperties(bounds, spuBrandTO);
            spuBrandTO.setSpuId(spuInfoId);
            R saveSpuBrands = couponFeignService.saveSpuBrands(spuBrandTO);
            if (saveSpuBrands.getCode() != 0){
                log.error("远程保存spu积分信息失败");
            }

        }
        //保存spu对应的sku信息
        List<Skus> skus = saveVO.getSkus();
        if (!ObjectUtils.isEmpty(skus)) {
            skus.forEach( item -> {
                //这里是来获取默认图片
                String defaultImg = "";
                for (Images image : item.getImages()) {
                    if (image.getDefaultImg() == 1){
                        defaultImg = image.getImgUrl();
                    }
                }
                SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
                BeanUtils.copyProperties(item, skuInfoEntity);
                skuInfoEntity.setCatalogId(saveVO.getCatalogId());
                skuInfoEntity.setBrandId(saveVO.getBrandId());
                skuInfoEntity.setSaleCount(0L);
                skuInfoEntity.setSpuId(spuInfoId);
                skuInfoEntity.setSkuDefaultImg(defaultImg);
                //保存sku的基本信息 pms_sku_info
                skuInfoService.saveSkuInfo(skuInfoEntity);
                //获取到sku的id
                Long skuId = skuInfoEntity.getSkuId();
                //保存sku的图片信息 pms_sku_images
                List<Images> imagesList = item.getImages();
                if (!ObjectUtils.isEmpty(imagesList)) {
                    List<SkuImagesEntity> skuImageCollect = imagesList.stream().map(imager -> {
                        SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                        skuImagesEntity.setSkuId(skuId);
                        skuImagesEntity.setDefaultImg(imager.getDefaultImg());
                        skuImagesEntity.setImgUrl(imager.getImgUrl());
                        return skuImagesEntity;
                    }).filter( entity ->{
                        //返回true就是需要,false就是过滤掉
                        return !StringUtils.isEmpty(entity.getImgUrl());
                    }).collect(Collectors.toList());
                    skuImagesService.saveImages(skuImageCollect);
                }
                //保存sku的销售属性信息 pms_sku_sale_attr_value
                List<Attr> skuAttr = item.getAttr();
                if (!ObjectUtils.isEmpty(skuAttr)) {
                    List<SkuSaleAttrValueEntity> skuSaleAttrValueList = skuAttr.stream().map(skuattr -> {
                        SkuSaleAttrValueEntity saleAttrValue = new SkuSaleAttrValueEntity();
                        BeanUtils.copyProperties(skuattr, saleAttrValue);
                        saleAttrValue.setSkuId(skuId);
                        return saleAttrValue;
                    }).collect(Collectors.toList());
                    skuSaleAttrValueService.saveSkuSaleAttrList(skuSaleAttrValueList);
                }

                //保存sku的优惠满减信息 gulimall_sms -> sms_sku_ladder \ sms_sku_full_reduction \ sms_member_price
                SkuReductionTO skuReductionTO = new SkuReductionTO();
                BeanUtils.copyProperties(item, skuReductionTO);
                skuReductionTO.setSkuId(skuId);
                skuReductionTO.setMemberPrice(item.getMemberPrice());
                if (skuReductionTO.getFullCount() > 0 || skuReductionTO.getFullPrice().compareTo(new BigDecimal("0")) ==1){
                    R saveSkuReduction = couponFeignService.saveSkuReduction(skuReductionTO);
                    if (saveSkuReduction.getCode() != 0 ){
                        log.error("远程保存sku优惠信息失败");
                    }
                }
            });
        }
    }

    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        QueryWrapper<SpuInfoEntity> wrapper = new QueryWrapper<SpuInfoEntity>();
        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)){
            wrapper.and( (w) ->{
                w.eq("id",key).or().like("spu_name",key);
            });
        }
        String status = (String) params.get("status");
        if (!StringUtils.isEmpty(status)){
            wrapper.eq("publish_status",status);
        }
        String brandId = (String) params.get("brandId");
        if (!StringUtils.isEmpty(brandId) && !"0".equals(brandId)){
            wrapper.eq("brand_id",brandId);
        }
        String catelogId = (String) params.get("catelogId");
        if (!StringUtils.isEmpty(catelogId) && !"0".equals(catelogId)){
            wrapper.eq("catalog_id",catelogId);
        }
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                wrapper
        );
        //将品牌id进行查询赋值给品牌名
        List<SpuInfoEntity> records = page.getRecords();
        if (!ObjectUtils.isEmpty(records)){
            records = records.stream().map( item ->{
                Long id = item.getBrandId();
                String name = brandService.getById(id).getName();
                item.setBrandName(name);
                Long catalogId = item.getCatalogId();
                String cataLogName = categoryService.getById(catalogId).getName();
                item.setCatalogName(cataLogName);
                return item;
            }).collect(Collectors.toList());
        }
        return new PageUtils(page);
    }

    @Override
    public void up(Long spuId) {
        //查出当前spuid对应的sku信息，品牌名称
        List<SkuInfoEntity> skus = skuInfoService.getSkusBySpuId(spuId);
        List<Long> skuIdList = skus.stream().map(SkuInfoEntity::getSkuId).collect(Collectors.toList());
        //这里是获取spu所有的属性值
        List<ProductAttrValueEntity> baseAttrs = attrValueService.baseAttrListforspu(spuId);
        //将属性的id进行返回
        List<Long> attrIds = baseAttrs.stream().map(item -> {
            return item.getAttrId();
        }).collect(Collectors.toList());
        //将属性id去属性表里面进行查询看是否能被检索
        List<Long> searchAttrIds = attrService.selectSearchAttrs(attrIds);
        //将能被检索的id转换成set集合
        Set<Long> idSet = new HashSet<>(searchAttrIds);
        //找出该spuid能被检索的属性,并进行封装
        List<SkuEsModel.Attrs> attrsList =baseAttrs.stream().filter(item -> {
            return idSet.contains(item.getAttrId());
        }).map(res ->{
            SkuEsModel.Attrs attrs1 = new SkuEsModel.Attrs();
            BeanUtils.copyProperties(res, attrs1);
            return attrs1;
        }).collect(Collectors.toList());
        Map<Long, Boolean> stockMap = null;
        try {
            //远程调用查看是否有库存
            R skuHasStock = wareFeignService.getSkuHasStock(skuIdList);
            TypeReference<List<SkuHasStockVO>> typeReference = new TypeReference<List<SkuHasStockVO>>() {
            };
            //将返回的参数进行处理
            stockMap = skuHasStock.getData(typeReference).stream().collect(Collectors.toMap(SkuHasStockVO::getSkuId, item -> item.getHasStock()));
        }catch (Exception e){
            log.error("库存服务查询异常：原因{}", e);
        }
        //封装每个sku的信息
        Map<Long, Boolean> finalStockMap = stockMap;
        //进行数据的绑定
        List<SkuEsModel> skuEsModels = skus.stream().map(item -> {
            SkuEsModel skuEsModel = new SkuEsModel();
            //将共同属性进行拷贝
            BeanUtils.copyProperties(item, skuEsModel);
            //处理一些单独数据
            skuEsModel.setSkuPrice(item.getPrice());
            skuEsModel.setSkuImg(item.getSkuDefaultImg());
            //设置库存信息
            if (finalStockMap == null) {
                skuEsModel.setHasStock(true);
            } else {
                skuEsModel.setHasStock(finalStockMap.get(item.getSkuId()));
            }
            //TODO 热度评分。0
            skuEsModel.setHotScore(0L);
            //设置品牌名称
            BrandEntity brand = brandService.getById(skuEsModel.getBrandId());
            if (!ObjectUtils.isEmpty(brand)) {
                skuEsModel.setBrandName(brand.getName());
                skuEsModel.setBrandImg(brand.getLogo());
            }
            //设置分类名称
            CategoryEntity category = categoryService.getById(skuEsModel.getCatalogId());
            if (!ObjectUtils.isEmpty(category)) {
                skuEsModel.setCatalogName(category.getName());
            }
            //设置检索属性
            skuEsModel.setAttrs(attrsList);
            return skuEsModel;
        }).collect(Collectors.toList());
        //发送给es进行保存
        R resp = searchFeignService.productStatusUp(skuEsModels);
        if (resp.getCode() == 0){
            baseMapper.updateSpuStatus(spuId, ProductConstant.StatusEnum.SPU_UP.getCode());
        }else {
            //远程调用失败
            //TODO 重复调用？重试机制
        }

    }

}